package com.heatup.apt.management.service.impl;

import com.baomidou.mybatisplus.mapper.*;
import com.heatup.apt.common.dao.user.UserSignMapper;
import com.heatup.apt.management.controller.*;
import com.heatup.apt.management.pay.*;
import com.heatup.apt.management.service.order.*;
import com.heatup.apt.management.util.*;
import com.heatup.apt.common.constants.OrderContants;
import com.heatup.apt.common.constants.UserConstants;
import com.heatup.apt.common.dao.*;
import com.heatup.apt.common.dao.store.StoreInfoMapper;
import com.heatup.apt.common.dao.user.UserAccountConsumeMapper;
import com.heatup.apt.common.dao.user.UserInfoMapper;
import com.heatup.apt.common.dao.user.UserProductServiceMapper;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.common.util.SetUtil;
import com.heatup.apt.common.util.StringUtil;
import com.heatup.apt.model.api.OrderInfoResultModel;
import com.heatup.apt.model.company.CompanyStaffConsume;
import com.heatup.apt.model.coupon.CouponDetail;
import com.heatup.apt.model.course.*;
import com.heatup.apt.model.management.SysUser;
import com.heatup.apt.model.order.*;
import com.heatup.apt.model.store.StoreInfo;
import com.heatup.apt.model.user.UserAccountConsume;
import com.heatup.apt.model.user.UserInfo;
import com.heatup.apt.model.user.UserProductService;
import com.heatup.apt.model.user.UserSign;
import org.slf4j.*;
import org.springframework.stereotype.*;

import javax.annotation.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.math.*;
import java.util.*;

@Service
public class OrderServiceImpl extends BaseController implements OrderService {
	@Resource
    private OrderInfoMapper orderInfoMapper;
	@Resource
	private OrderDetailMapper orderDetailMapper;
	@Resource
    private CourseInfoMapper courseInfoMapper;

    @Resource
    private StoreInfoMapper storeInfoMapper;

    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private CourseCoachMapper courseCoachMapper;

    @Resource
	private OrderInfoResultMapper orderInfoResultMapper;
    @Resource
    private CouponDetailMapper couponDetailMapper;
    @Resource
	private UserAccountConsumeMapper userAccountConsumeMapper;
    @Resource
	private CompanyStaffConsumeMapper companyStaffConsumeMapper;
    @Resource
    private VipPurchaseLogMapper vipPurchaseLogMapper;
    @Resource
    private UserProductServiceMapper userProductServiceMapper;
    @Resource
    private CourseSignMapper courseSignMapper;
    @Resource
	private UserSignMapper userSignMapper;
    
    private Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);
    

	/**
	 * 团课列表的获取
	 * 状态：
	 *  1.已支付待开始
	 *  2.已支付排队中
	 *  3.已结束
	 *  4.主动取消
	 *  5.被动取消
	 *  6.待支付
	 *  7.已退款
	 *  
	 */
    @Override
	public List<OrderInFoToTK> getOrderListByTK(Map<String, Object> map) throws Exception {
		Map<String,Object> mapWhere = new HashMap<String,Object>();
		List<Map<String,Object>> listData = new ArrayList<Map<String,Object>>();
		Date now = new Date(); 
		// 获取到所有的团课订单
		String type = (String)map.get("type");
		mapWhere.put("no_refund","1");
		mapWhere.put("course_stime",map.get("course_stime"));
		mapWhere.put("course_etime",map.get("course_etime"));
		mapWhere.put("course_id",map.get("course_id"));
		mapWhere.put("mobile",map.get("mobile"));
		mapWhere.put("pageNum",map.get("pageNum"));
		mapWhere.put("pageCount",map.get("pageCount"));
		mapWhere.put("tradeId",map.get("tradeId"));
		mapWhere.put("coachId",Integer.valueOf((String) map.get("coachId")));
		mapWhere.put("userId", map.get("userId"));
		mapWhere.put("userName", map.get("userName"));
		String store_ids = (String) map.get("store_id");
		int store_id = Integer.valueOf(store_ids);
		if(store_id != 0){
			mapWhere.put("store_id",store_id);
		}	
		// 已付款待开始
		if("1".equals(type)){
			String start_time = "";
			Date newTime = new Date();
			start_time	= DateUtils.format(newTime,DateUtils.datePatternAllHH);
			mapWhere.put("start_time",start_time);
			mapWhere.put("pay_status",1);
			mapWhere.put("order_status",1);
			mapWhere.put("cancel",0);
		}
		// 已付款排队中
		else if("2".equals(type)){
			mapWhere.put("order_status",3);
			mapWhere.put("pay_status",1);
			mapWhere.put("cancel",0);
		}
		// 已结束
		else if("3".equals(type)){
			String end_time = "";
			Date newTime = new Date();
			end_time	= DateUtils.format(newTime,DateUtils.datePatternAllHH);
			mapWhere.put("end_time",end_time);
			mapWhere.put("pay_status",1);
			mapWhere.put("order_status",4);
			mapWhere.put("cancel",0);
		}
		// 主动取消
		else if("4".equals(type)){
			mapWhere.put("order_status",2);
			mapWhere.put("pay_status",1);
			mapWhere.put("cancel",1);
		}
		// 待支付
		else if("5".equals(type)){
			mapWhere.put("pay_status",2); 
		}
		// 已退款
		else if("6".equals(type)){
			mapWhere.put("refund","1");
			mapWhere.remove("no_refund");
			mapWhere.remove("pay_status");
			mapWhere.put("cancel_status", "4");
		}
		// 被动取消
		else if("7".equals(type)){
			mapWhere.put("order_status",2);
			mapWhere.put("pay_status",1);
			mapWhere.put("cancel",2);
		}
		
		List<OrderInFoToTK> mapd = orderInfoMapper.getOrderListByTK(mapWhere);
		return mapd;
	}



	/**
	 * 获取不是删除数据的门店
	 */
	public List<Map<String,Object>> getStoreList(Map<String,Object> map){
		Map<String,Object> dataMap = null;//new HashMap<String,Object>();
		List<Map<String,Object>> listM = new ArrayList<Map<String,Object>>();
		EntityWrapper<StoreInfo> entityWrapper= new EntityWrapper<StoreInfo>();
		//storeInfoExample.or().andStatusNotEqualTo("5");
		entityWrapper.where("status != {0}", "5");
		List<StoreInfo> list = storeInfoMapper.selectList(entityWrapper);
		for(StoreInfo s:list){
			dataMap = new HashMap<String,Object>();
			dataMap.put("code", s.getId());
			dataMap.put("name", s.getStoreName());
			listM.add(dataMap);
		}
		return listM;
	}
	
	/**
	 * 获取私教课程数据列表
	 */
	@Override
	public List<OrderInFoToTK> getOrderListBySJ(Map<String, Object> map) throws Exception {
		List<OrderInFoToTK> listO = new ArrayList<OrderInFoToTK>();
		Map<String,Object> mapWhere = new HashMap<String,Object>();
		String type = (String)map.get("type");
		mapWhere.put("course_stime",map.get("course_stime"));
		mapWhere.put("course_etime",map.get("course_etime"));
		mapWhere.put("course_id",map.get("course_id"));
		mapWhere.put("mobile",map.get("mobile"));
		mapWhere.put("pageNum",map.get("pageNum"));
		mapWhere.put("pageCount",map.get("pageCount"));
		mapWhere.put("tradeId",map.get("tradeId"));
		mapWhere.put("coachId",Integer.valueOf((String) map.get("coachId")));
		mapWhere.put("userId", map.get("userId"));
		mapWhere.put("userName", map.get("userName"));
		String store_ids = (String) map.get("store_id");
		int store_id = Integer.valueOf(store_ids);
		if(store_id != 0){
			mapWhere.put("store_id",store_id);
		}
		// 已支付
		if("1".equals(map.get("type"))){
			mapWhere.put("pay_status",1);
			mapWhere.put("order_status",1);
		}
		// 已结束
		else if("2".equals(map.get("type"))){
			mapWhere.put("pay_status",1);
			mapWhere.put("order_status",4);
		}
		// 待支付
		else if("3".equals(map.get("type"))){
			mapWhere.put("pay_status",2);
		}
		// 已退款 
		else if("4".equals(map.get("type"))){
			mapWhere.put("refund","success");
			mapWhere.put("pay_status",1);
			/*mapWhere.put("pay_status", "4");*/
			mapWhere.remove("pay_status");
			mapWhere.put("cancel_status", "4");
		}
		
		listO = orderInfoMapper.getOrderListBySJ(mapWhere);
		
		return listO;
	}
	/**
	 * 获取檬营list
	 */
	@Override
	public List<OrderInFoToTK> getOrderListByMY(Map<String, Object> map) throws Exception {
		Map<String,Object> mapWhere = new HashMap<String,Object>();
		List<OrderInFoToTK> listDate = new ArrayList<OrderInFoToTK>();
		Integer pageNum = (Integer) map.get("pageNum"); 
		String course_stime =(String) map.get("course_stime");
		String course_etime =(String) map.get("course_etime");
		String course_id = (String)map.get("course_id");
		String mobile = (String)map.get("mobile");
		String store_ids = (String)map.get("store_id");
		System.out.println(store_ids);
		int store_id = Integer.valueOf(store_ids);
		mapWhere.put("pay_status","1");
		mapWhere.put("course_etime",course_etime);
		mapWhere.put("course_stime",course_stime);
		mapWhere.put("course_id",course_id);
		mapWhere.put("mobile",mobile);
		mapWhere.put("order_status",'1');
		mapWhere.put("pageNum",pageNum);
		mapWhere.put("pageCount",map.get("pageCount"));
		mapWhere.put("tradeId",map.get("tradeId"));
		mapWhere.put("userId", map.get("userId"));
		mapWhere.put("userName", map.get("userName"));
		if(store_id != 0){
			mapWhere.put("store_id",store_id);
		}
		// 已支付 成营
		if("1".equals(map.get("type"))){
			mapWhere.put("chen","2");
			mapWhere.put("order_status",1);
		}
		// 已支付 未成营
		else if("2".equals(map.get("type"))){
			mapWhere.put("weichen","2");
			mapWhere.put("order_status",'1');
		}
		// 已结束
		else if("3".equals(map.get("type"))){
			String end_time = "";
			Date newTime = new Date();
			end_time	= DateUtils.format(newTime,DateUtils.datePatternAllHH);
			mapWhere.put("end_time",end_time);
			mapWhere.put("order_status",'4');
		}
		// 待支付
		else if("4".equals(map.get("type"))){
			mapWhere.put("pay_status",'2');
		}
		// 被动取消
		else if("5".equals(map.get("type"))){
			mapWhere.put("cancel","2");
			mapWhere.put("order_status",2);
			
		}
		// 已退款 
		else if("6".equals(map.get("type"))){
			mapWhere.put("tuikuan","1");
			mapWhere.put("order_status",'2');
			/*mapWhere.put("pay_status", "4");*/
			mapWhere.remove("pay_status");
			mapWhere.put("cancel_status", "4");
		}// 主动取消
		else if("7".equals(map.get("type"))){
			mapWhere.put("cancel","1");
			mapWhere.put("order_status",2);
		}// 
		else if("8".equals(map.get("type"))){
			
		}else if("9".equals(map.get("type"))){
			mapWhere.put("chen","2");
			mapWhere.put("order_status",3);
		}
		
		listDate = orderInfoMapper.getOrderListByMY(mapWhere);
		return listDate;
	}
	/**
	 * 自助健身list
	 */
	@Override
	public List<OrderInFoToTK> getOrderListByZZ(Map<String, Object> map) throws Exception {
		Map<String,Object> mapWhere = new HashMap<String,Object>();
		List<OrderInFoToTK> listDate = new ArrayList<OrderInFoToTK>();
		
		Integer pageNum = (Integer) map.get("pageNum"); 
		String course_stime =(String) map.get("course_stime");
		String course_etime =(String) map.get("course_etime");
		String title = (String)map.get("title");
		String mobile = (String)map.get("mobile");
		String store_ids = (String)map.get("store_id");
		int store_id = Integer.valueOf(store_ids);
		mapWhere.put("pageNum",pageNum);
		mapWhere.put("pageCount",map.get("pageCount"));
		mapWhere.put("tradeId",map.get("tradeId"));
		mapWhere.put("userId", map.get("userId"));
		mapWhere.put("userName", map.get("userName"));
		/*if(course_stime != null){
			mapWhere.put("course_stime",DateUtils.toDate(course_stime,DateUtils.datePattern));
		}
		if(course_etime != null){
			mapWhere.put("course_etime",DateUtils.toDate(course_etime,DateUtils.datePattern));
		}*/
		mapWhere.put("course_etime",course_etime);
		mapWhere.put("course_stime",course_stime);
		mapWhere.put("title",title);
		mapWhere.put("mobile",mobile);
		if(store_id != 0){
			mapWhere.put("store_id",store_id);
		}
		
		mapWhere.put("pay_status",'1');
		// 已支付 
		if("1".equals(map.get("type"))){
			mapWhere.put("order_status","1");
		}
		// 已结束
		else if("2".equals(map.get("type"))){
			String end_time = "";
			Date newTime = new Date();
			end_time	= DateUtils.format(newTime,DateUtils.datePatternAllHH);
			mapWhere.put("end_time",end_time);
			mapWhere.put("pay_status",'1');
			mapWhere.put("order_status","4");
		}
		// 待支付
		else if("3".equals(map.get("type"))){
			mapWhere.put("pay_status",'2');
		}
		// 已取消
		else if("4".equals(map.get("type"))){
			mapWhere.put("quxiao",2);
			mapWhere.put("order_status","2");
		}
		// 已退款 
		else if("5".equals(map.get("type"))){
			mapWhere.put("tuikuan",2);
			mapWhere.put("order_status","2");
			/*mapWhere.put("pay_status", "4");*/
			mapWhere.remove("pay_status");
			mapWhere.put("cancel_status", "4");
		}
		listDate = orderInfoMapper.getOrderListByZZ(mapWhere); 
		return listDate;
	}
	/**
	 * 创建退款订单
	 */
	@Override
	public int createdRefundOrder(Map<String, Object> map) {
		OrderRefund orderR = new OrderRefund();
		OrderInfo orderInfo = null;
		int orderId =(int)map.get("orderId");
		int biaoshi =(int)map.get("biaoshi");
		orderInfo = orderInfoMapper.selectById(orderId);
		int count = orderInfoMapper.queryOrderRefundByOrderId(orderId);
		UserInfo userInfo  = userInfoMapper.selectById(orderInfo.getUserId());
		// 防止多笔退款
		if(count > 0){
			return 1;
		}else{
			//调用退款接口 返回数据
			Map<String, Object> refundMap = new HashMap<String,Object>();
			if(orderInfo.getPayType() == OrderContants.PAY_TYPE_PERSON_ACCOUNT){
				BigDecimal accountAmt = userInfo.getAccountAmt().add(orderInfo.getAmount());
				userInfo.setAccountAmt(accountAmt);
				int bool = userInfoMapper.updateSelectiveById(userInfo);
				if(bool > 0){
					refundMap.put("result_code", "SUCCESS");
					refundMap.put("refund_id",String.valueOf(orderInfo.getId()));
					logger.info("========================================= userAccount RefundOrder =====================");
				}else{
					refundMap.put("result_code", "FAIL");
					refundMap.put("NOTENOUGH","退款失败");
				}
				
			}else if(orderInfo.getPayType().intValue() == OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT){
				// 微信+个人储值卡支付退款
				// 1先退个人储值卡的金额
				BigDecimal accountAmt = userInfo.getAccountAmt().add(orderInfo.getConsumeAmt());
				userInfo.setAccountAmt(accountAmt);
				int bool = userInfoMapper.updateSelectiveById(userInfo);
				logger.info("========================================= company and weixin refund bool:"+bool+"=====================");
				if(bool > 0){
					// 2再退微信支付金额
					refundMap = RefundUtil.wechatRefund1(orderInfo.getOrderNumber(), orderInfo.getWeixinAmt(),
							orderInfo.getWeixinAmt());
				}else{
					refundMap.put("result_code", "FAIL");
					refundMap.put("NOTENOUGH","退款失败");
				}
				
			}else if(orderInfo.getPayType().intValue() == OrderContants.PAY_TYPE_WECHAT){
				refundMap = RefundUtil.wechatRefund1(orderInfo.getOrderNumber(), orderInfo.getAmount(), orderInfo.getAmount());
				logger.info("=================orderInfo  RefundOrder ==================================================");
			}else if(orderInfo.getPayType().intValue() == OrderContants.PAY_TYPE_COMPANY_ACCOUNT){
				// 企业储值卡订单退款
				CompanyStaffConsume companyStaffConsumeQuery = new CompanyStaffConsume();
				companyStaffConsumeQuery.setOrderId(orderInfo.getId());
				companyStaffConsumeQuery.setOrderStatus(OrderContants.OrderStatus.NORMAL.getIndex());
				CompanyStaffConsume companyStaffConsume = companyStaffConsumeMapper.selectOne(companyStaffConsumeQuery);
				if (companyStaffConsume != null && companyStaffConsume.getId() != null) {
					companyStaffConsume.setId(null);
					companyStaffConsume.setPayTime(null);
					companyStaffConsume.setCancelTime(new Date());
					companyStaffConsume.setOrderStatus(OrderContants.OrderStatus.CANCEL.getIndex());
				}
				boolean boolC = companyStaffConsumeMapper.insertSelective(companyStaffConsume) > 0;
				if(!boolC){
					refundMap.put("result_code", "FAIL");
					refundMap.put("NOTENOUGH","退款失败");
				}else{
					refundMap.put("result_code", "SUCCESS");
					refundMap.put("refund_id",String.valueOf(orderInfo.getId()));
				}
			}else if(orderInfo.getPayType().intValue() == OrderContants.PAY_TYPE_COMPANY_WECHAT_ACCOUNT){
				refundMap = createCompanyStaffConsume(orderInfo, orderInfo.getAmount(), orderInfo.getCompanyAmt());
				if("SUCCESS".equals(refundMap.get("result_code"))){
					// 2再退微信支付金额
					refundMap = RefundUtil.wechatRefund1(orderInfo.getOrderNumber(), orderInfo.getWeixinAmt(),
							orderInfo.getWeixinAmt());
				}
			}
			
			if("FAIL".equals(refundMap.get("result_code"))){
				if("NOTENOUGH".equals(refundMap.get("err_code"))){
					return -2;
				}
				return -1;
			}else if("SUCCESS".equals(refundMap.get("result_code"))){
				String refundId =(String) refundMap.get("refund_id");
				double refundFee = orderInfo.getAmount().doubleValue();
				String refundStatus = "success";
				int refundType = 0 ;
				int payType = orderInfo.getPayType();
				String remark = "退款";
				if(payType == OrderContants.PAY_TYPE_WECHAT || payType == OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT){
					refundType = 1;
					remark = "退到微信账户中";
					refundFee = orderInfo.getWeixinAmt().doubleValue();
					refundStatus = "success";
				}else if(payType == OrderContants.PAY_TYPE_PERSON_ACCOUNT){
					refundType = 2;
					remark = "退到个人账户中";
				}else if(payType == OrderContants.PAY_TYPE_COMPANY_ACCOUNT){
					refundType = 3;
					remark = "退到企业账户中";
				}else if(payType == OrderContants.PAY_TYPE_COMPANY_WECHAT_ACCOUNT){
					refundType = 1;
					remark = "退到微信账户中";
					refundFee = orderInfo.getWeixinAmt().doubleValue();
					refundStatus = "success";
				}
				SysUser sysUser = this.getUserInfo();
				List<OrderRefund> listR = new ArrayList<OrderRefund>();
				Date created_time = new Date();
				orderR = createOrderRefund(orderInfo, Integer.valueOf(refundType), refundStatus, refundId, orderInfo.getAmount(), BigDecimal.valueOf(refundFee), sysUser, remark);
				/*orderR.setOrderId(orderId);
				orderR.setRefundType(refundType);
				orderR.setRefundNo(refund_id);
				orderR.setRefundFee(refund_fee);
				orderR.setTotalFee(orderInfo.getAmount().doubleValue());
				orderR.setRefundStatus("processing");//这里统一给退款中,然后在每天跑定时任务的时候在更新状态值
				orderR.setUserId(orderInfo.getUserId());
				orderR.setRefundChanne("original");
				orderR.setRefundFashion("1");
				orderR.setCreatedTime(created_time);
				orderR.setCreatedBy(String.valueOf(sysUser.getId()));
				orderR.setRemark(remark);*/
				int zhunatai = 0 ;
				if(orderInfo.getPayType().intValue() != OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT 
						&& orderInfo.getPayType().intValue() != OrderContants.PAY_TYPE_COMPANY_WECHAT_ACCOUNT){
					zhunatai = orderInfoMapper.createdRefundOrder(orderR);
				}else{
					listR.add(orderR);
				}
				
				// 增加退款表示
				orderInfo.setPayStatus("4");// 表示已退款
				orderInfo.setOrderStatus(OrderContants.OrderStatus.CANCEL.getStatus());
				int refundS = orderInfoMapper.updateSelectiveById(orderInfo);
				logger.info(" insert refundorder  and update orderInfo status 4  RefundOrder Status"+zhunatai+"  orderInfo Status："+refundS);
				
				if(orderInfo.getPayType().intValue() == OrderContants.PAY_TYPE_PERSON_ACCOUNT 
						|| orderInfo.getPayType().intValue() == OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT){
					BigDecimal userAccount = new BigDecimal(-1);
					if(orderInfo.getPayType().intValue() == OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT){
						userAccount = userAccount.multiply(orderInfo.getConsumeAmt());
						/*OrderRefund orderRefund = new OrderRefund();
						orderRefund.setOrderId(orderId);
						orderRefund.setRefundType(OrderContants.PAY_TYPE_PERSON_ACCOUNT);
						orderRefund.setRefundNo(String.valueOf(orderId));
						orderRefund.setRefundFee(orderInfo.getConsumeAmt().doubleValue());
						orderRefund.setTotalFee(refund_fee);
						orderRefund.setRefundStatus("success");//这里统一给退款中,然后在每天跑定时任务的时候在更新状态值
						orderRefund.setUserId(orderInfo.getUserId());
						orderRefund.setRefundChanne("original");
						orderRefund.setRefundFashion("1");
						orderRefund.setCreatedTime(created_time);
						orderRefund.setCreatedBy(String.valueOf(sysUser.getId()));
						orderRefund.setRemark("微信+储值卡订单类型退款，储值卡");*/
						
						listR.add(createOrderRefund(orderInfo, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, "success" , String.valueOf(orderId), orderInfo.getAmount(), orderInfo.getConsumeAmt(), sysUser, "微信+储值卡订单类型退款，储值卡"));
						int zhunatai1 = orderInfoMapper.createdRefundOrderList(listR);//orderInfoMapper.createdRefundOrder(orderR);
						logger.info("========= createdRefundOrder bool:"+zhunatai1);
						zhunatai = zhunatai1;
					}else{
						userAccount = userAccount.multiply(orderInfo.getAmount());
					}
					//向储值卡消费记录中添加一条记录
					UserAccountConsume userAccountConsume = new UserAccountConsume();
					userAccountConsume.setUserId(orderInfo.getUserId());
					userAccountConsume.setConsumeType(String.valueOf(1));
					
					userAccountConsume.setConsumeAmt(userAccount);
					userAccountConsume.setOrderId(orderInfo.getId());
					userAccountConsume.setRemark("后台管理取消订单插入数据");
					userAccountConsume.setCreateTime(new Date());
					int userBoll = userAccountConsumeMapper.insert(userAccountConsume);
					logger.info("================================createdRefundOrder ：insert userAccountConsume bool:"+userBoll);
				}else if(orderInfo.getPayType().intValue() == OrderContants.PAY_TYPE_COMPANY_WECHAT_ACCOUNT){
					listR.add(createOrderRefund(orderInfo, OrderContants.PAY_TYPE_COMPANY_WECHAT_ACCOUNT, "success", String.valueOf(orderId), orderInfo.getAmount(), orderInfo.getCompanyAmt(), sysUser, "微信+企业储值卡订单类型退款，企业储值卡"));
					zhunatai = orderInfoMapper.createdRefundOrderList(listR);
				}
				updateVipOrder(orderInfo, userInfo);
				return zhunatai;
			}
		}
		
		return -1;
	}
	/**
	 * 修改订单状态:取消订单
	 * 1正常 
	 * 2取消,
	 * 3排队，
	 * 4完成
	 */
	@Override
	public int updateOrder(Map<String, Object> map) {
		Map<Object,Object> mapWhere = new HashMap<Object,Object>();
		String ids = (String) map.get("orderId");
		int id =Integer.valueOf(ids) ;
		String type = (String) map.get("type");
		// 修改订单之前先查一次啊防止多次提交
		OrderInfo orderInfo = orderInfoMapper.selectById(id);
		if (orderInfo.getCancel() != 0 || "2".equals(orderInfo.getOrderStatus())) {
			logger.info("===================== 订单重复提交 ===========================");
			return -1;
		}
		// 查询订单信息
		OrderInfoResultModel orderInfoResultModel = new OrderInfoResultModel();
		orderInfoResultModel = orderInfoResultMapper.selectByOrderId(Integer.valueOf(ids));
		Integer orderType = orderInfoResultModel.getOrderType();
		int bool = 0 ;
		// 团课订单
		if(OrderContants.OrderType.team_course.getIndex() == orderType){
			bool = cancelTeamCourseOrder(orderInfoResultModel.getServicePrice().getCourseId(),orderInfoResultModel,orderInfoResultModel.getPayStatus());
		}else if(OrderContants.OrderType.fun_camp.getIndex() == orderType){
			// 檬营订单取消
			cancelCampCourseOrder(orderInfoResultModel.getServicePrice().getCourseId(),orderInfoResultModel,orderInfoResultModel.getPayStatus());
		}
		int order_status = 1;
		if("1".equals(type)){
			order_status = 2;
			
		}
		mapWhere.put("orderId",id);
		mapWhere.put("order_status",order_status);
		mapWhere.put("cancel",2);
		orderInfo.setOrderStatus(String.valueOf(order_status));
		orderInfo.setCancel(2);// 表示被动取消 
		orderInfo.setUserCancelTime(new Date()); // 取消时间
		orderInfo.setUpdatedTime(new Date());
		orderInfo.setCancelBackmoney(1);// 表示是可退款的
		int status = orderInfoMapper.updateSelectiveById(orderInfo);
//		int status = (Integer)orderInfoMapper.updateStatusOrder(mapWhere);
		
		return status;
	}
	/**
	 * 根据课程id获取课程计划列表
	 */
	@Override
	public List<CourseSchedule> getCourseScheduleList(Map<String, Object> map) {
		String ids = (String) map.get("orderId");
		int id = Integer.valueOf(ids);
		OrderInfo orderI = orderInfoMapper.selectById(id);
		map.put("serviceId",orderI.getServiceId());
		List<CourseSchedule> list = orderInfoMapper.getCourseScheduleList(map);
		return list;
	}

	/**
	 * 获取订单的总课时
	 */
	@Override
	public OrderDetail getOrderDetail(Map<String, Object> map) {
		String orderIds = (String) map.get("orderId");
		int orderId = Integer.valueOf(orderIds);
		return orderDetailMapper.queryOrderDetailByOrderId(orderId);
	}
	

	/**
	 * 根据订单id获取课程信息
	 */
	@Override
	public Map<Object, Object> getCourseInfoById(Map<String, Object> map) {
		
		Map<Object, Object> resultMap = new HashMap<Object, Object>();
		
		String orderIds = (String) map.get("orderId");
		int orderId = Integer.valueOf(orderIds);

		// 根据订单查询日程
        List<CourseSign> course_sign_list = courseSignMapper.queryCourseSignByOrderId(orderId);
        OrderDetail orderDetail = orderDetailMapper.queryOrderDetailByOrderId(orderId);
		resultMap.put("course_sign_list", course_sign_list);
		resultMap.put("course_sign_count", course_sign_list.size());
		resultMap.put("store_list", "[]");
		int num = 0;
		if (SetUtil.isNotNull(course_sign_list)) {
			Integer courseId = course_sign_list.get(0).getCourseId();
			CourseInfo c = courseInfoMapper.selectById(courseId);
			if (null != c) {
				num = (c.getPeriods() == 0 ?orderDetail.getCourseCount():c.getPeriods());
			}
			List<StoreInfo> store_list = storeInfoMapper.selectByCourseId(courseId);
			resultMap.put("store_list", store_list);
        }
		resultMap.put("num", num);
		return resultMap;
	}

	@Override
	public List<OrderRefund> getOrderRefundList() {
		List<OrderRefund> list = orderInfoMapper.getOrderRefundList();
		return list;
	}

	@Override
	public int updateOrderRefund(OrderRefund orderRefund) {
		// TODO Auto-generated method stub
		return 0;
	}

	
	
	/**
	 * 销课
	 * <P>Author : fangxiaowen </P>      
	 * <P>Date : 2016年10月21日 </P>
	  * @param num 课程顺序
	 * @param id 签到ID
	 * @param courseId 课程ID
	 * @param storeId 门店ID
	 * @param startTime 开始时间
	 * @param closeTime 关闭时间
	 * @return
	 * @see com.heatup.apt.management.service.order.OrderService(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public Map updateCancelCourse(String num, String id, String courseId,
			String storeId,String orderId,String startTime, String closeTime,Integer userId) throws Exception{
		
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("num", num);
		map.put("orderId", orderId);

		// 因为教练端的私教课程改造 每一个私教课程的添加都会建立对应节数的日程
		// 销课的时候就把对应的私教日程给销课就可以了不需要在做其余的判断
		// 所有的销课必须都是添加到日程的课程才能销课
		CourseSign courseSign = courseSignMapper.selectById(Integer.valueOf(id));
		if (courseSign == null){
			map.put("status",-1);
			map.put("msg","该日程不存在");
			return map;
		}
		if (courseSign.getCoachId() == null){
			map.put("status",-1);
			map.put("msg","该日程没有添加教练不能销课");
			return map;
		}

		if ("1".equals(courseSign.getIsclose())){
			map.put("status",-1);
			map.put("msg","该日程已销课,不能重复销课");
			return map;
		}

		courseSign.setStartTime(DateUtils.toDate(startTime+":00", DateUtils.datePatternAllHH));
		courseSign.setCloseTime(DateUtils.toDate(closeTime+":00", DateUtils.datePatternAllHH));
		courseSign.setIsclose("1");
		int addCourseSignId = courseSignMapper.updateById(courseSign);

		if(addCourseSignId > 0){
			// 用户签到成功
			UserSign userSign = new UserSign();
			userSign.setUserId(courseSign.getUserId());
			userSign.setCourseId(courseSign.getCourseId());
			userSign.setOrderId(courseSign.getOrderId());
			userSign.setCourseSignId(courseSign.getId());
			userSign.setOrderType(2);
			userSign.setSignTime(new Date());
			userSign.setRemark("管理后台帮用户签到");
			userSign.setStatus(1);
			userSign.setCreateTime(new Date());
			int addUserSignCount = userSignMapper.insert(userSign);
			if (addUserSignCount > 0) {
				map.put("status",0);
				map.put("msg","销课成功");
				return map;
			}
			else throw new RuntimeException("销课异常");
		}




		// old code
//		int sign_less_num = orderInfoMapper.queryCourseSignLessNum(map);
//		OrderDetail orderDetail = orderDetailMapper.queryOrderDetailByOrderId(Integer.valueOf(orderId));
//		if (Integer.valueOf(num) - 1 == sign_less_num) {
//
//            CourseCoach courseCoachDB = new CourseCoach();
//            courseCoachDB.setCourseId(Integer.valueOf(courseId));
//            EntityWrapper<CourseCoach> courseCoachEntityWrapper = new EntityWrapper<>(courseCoachDB);
//
//			List<CourseCoach> course_coach_list = courseCoachMapper.selectList(courseCoachEntityWrapper);
//			if (SetUtil.isNotNull(course_coach_list)) {
//				map.put("coachId", course_coach_list.get(0).getCoachId());
//			}
//			map.put("storeId", storeId);
//			map.put("startTime",startTime);
//			map.put("closeTime", closeTime);
//			map.put("id", Integer.valueOf(id));
//			int count = orderInfoMapper.updateCancelCourse(map);
//
//			map.clear();
//			map.put("orderId", orderId);
//
//			CourseInfo courseInfo = courseInfoMapper.selectById(Integer.valueOf(courseId));
//			if (null != courseInfo) {
//				/*int cs_count = courseInfo.getPeriods();*/
//				int cs_count = (orderDetail.getCourseCount() == 0?courseInfo.getPeriods():orderDetail.getCourseCount());
//				if (cs_count != 0 && StringUtil.isEquals(num, cs_count)) {
//					map.put("updatedBy", userId);
//					orderInfoMapper.updateOrderInfoStatus(map);
//				}
//			}
//			return count;
//		}else{
//			return -1;
//		}
		map.put("status",-1);
		map.put("msg","销课失败");
		return map;
	}
	// TODO
	/**
	 * 团课订单取消
	 * 这里的逻辑和前端的逻辑保持一致
	 * 后期优化直接就用api端的方法
	 * @param courseId 
	 * @param orderInfo
	 * @param orderStatus
	 * @return
	 */
	public int cancelTeamCourseOrder(int courseId, OrderInfoResultModel orderInfo,String orderStatus){
		logger.info("===============management  Team order cancel start ==============================================");
		OrderInfoResultModel dd = new OrderInfoResultModel();
		CourseInfo courseInfo = courseInfoMapper.selectById(courseId);
		int orderPerson = orderInfo.getOrderDetail().getPersonCount()==null?0:orderInfo.getOrderDetail().getPersonCount();
		int currentCount = courseInfo.getCurrentCount()==null?0:courseInfo.getCurrentCount();
		int waitCount = courseInfo.getWaitCount()==null?0:courseInfo.getWaitCount();
		logger.info("=============== management  orderPerson :" +orderPerson +"currentCount :"+ currentCount +" waitCount :"+ waitCount);
		//排队
		if(OrderContants.OrderStatus.WAIT.equals(orderStatus)){
			waitCount = waitCount - orderPerson;
			orderInfo.setCancelBackmoney(1);
		}
		else if(StringUtil.isEquals(OrderContants.OrderStatus.NORMAL.getStatus(), orderStatus)){
			currentCount =currentCount-orderPerson;


			//查询所有排队的订单
			List<OrderInfoResultModel> waitOrders = orderInfoResultMapper.selectWaitOrderByServiceId(orderInfo.getServiceId());
			if(waitOrders!=null && waitOrders.size()>0){
				int personCount=0;
				for(OrderInfoResultModel waitOrder:waitOrders){
					//当前订单人数
					int curOrderPersonCount = (waitOrder.getOrderDetail().getPersonCount()==null?0:waitOrder.getOrderDetail().getPersonCount());
					personCount +=curOrderPersonCount ;
					//当前课程的人数应该增加
					currentCount= currentCount+curOrderPersonCount;
					waitCount -= curOrderPersonCount;
					// 将排队等待的订单更新成预订成功
					waitOrder.setOrderStatus(OrderContants.OrderStatus.NORMAL.getStatus());
					waitOrder.setUpdatedBy(-1);
					waitOrder.setUpdatedTime(new Date());
					orderInfoMapper.updateSelectiveById(waitOrder);
					if(personCount>=orderPerson){
						break;
					}
				}
				logger.info("=============== management Team courseInfo order  cancel ==================================");
			}
		}
		//设置课程的当前人数和排队人数
		courseInfo.setCurrentCount(currentCount);
		courseInfo.setWaitCount(waitCount);
		int bool = courseInfoMapper.updateSelectiveById(courseInfo);
		logger.info("===============management  Team  order end ==============================================");
		
		return bool;
	}
	
	/**jxy
	 * 檬营订单取消
	 * @param courseId 课程ID
	 * @param orderInfo 订单信息
	 * @param orderStatus 订单状态
	 */
	private void cancelCampCourseOrder(int courseId, OrderInfoResultModel orderInfo, String orderStatus) {
		logger.info("===============management  fun_camp order cancel start ==============================================");
		CourseInfo courseInfo = courseInfoMapper.selectById(courseId);
		int orderPerson = orderInfo.getOrderDetail().getPersonCount()==null?0:orderInfo.getOrderDetail().getPersonCount();
		int currentCount = courseInfo.getCurrentCount()==null?0:courseInfo.getCurrentCount();
		int waitCount = courseInfo.getWaitCount()==null?0:courseInfo.getWaitCount();

        CourseInfoModel campCourse = courseInfoMapper.queryCampCourseById(orderInfo.getServicePrice().getCourseId());

		if(StringUtil.isEquals(OrderContants.OrderStatus.WAIT.getStatus(), orderStatus)){
			// 排队订单 退款
			orderInfo.setCancelBackmoney(1);
			
			waitCount = waitCount - orderPerson;
		}else if(StringUtil.isEquals(OrderContants.OrderStatus.NORMAL.getStatus(), orderStatus)){
            //查询所有排队的订单
			List<OrderInfoResultModel> waitOrders = orderInfoResultMapper.selectWaitOrderByServiceId(orderInfo.getServiceId());
			if(waitOrders!=null && waitOrders.size()>0){
				int personCount=0;
				for(OrderInfoResultModel waitOrder:waitOrders){
					int curOrderPersionCount = waitOrder.getOrderDetail().getPersonCount()==null?0:waitOrder.getOrderDetail().getPersonCount();
					personCount += curOrderPersionCount;
					//当前课程的人数应该增加
					currentCount = currentCount + curOrderPersionCount;
					waitCount = waitCount - curOrderPersionCount;
					// 将排队等待的订单更新成预订成功
					waitOrder.setOrderStatus(OrderContants.OrderStatus.NORMAL.getStatus());
					waitOrder.setUpdatedBy(-1);
					waitOrder.setUpdatedTime(new Date());
					orderInfoMapper.updateSelectiveById(waitOrder);
					if(personCount>=orderPerson){
						break;
					}
				}
				logger.info("===============management  fun_camp order cancel ........... ==============================================");
			} else {
				//未成营的订单数减少
				currentCount = courseInfo.getCurrentCount() - orderPerson;
			}
		}
		//设置课程的当前人数和排队人数
		courseInfo.setCurrentCount(currentCount);
		courseInfo.setWaitCount(waitCount);
		courseInfoMapper.updateSelectiveById(courseInfo);
		logger.info("===============management  fun_camp order cancel end ==============================================");
	}
	
	/**
	 * 订单查询导出
	 */
	@Override
	public String execlOrderListByType(HttpServletRequest request, HttpServletResponse response, String type)
			throws IOException {
		String fileName = DateUtils.format(new Date(),"yyyyMMddHHmmss");
		String orderType = request.getParameter("type");
		if("1".equals(orderType)){
			fileName = "团课订单"+fileName;
		}else if("2".equals(orderType)){
			fileName = "私教订单"+fileName;
		}else if("3".equals(orderType)){
			fileName = "檬营订单"+fileName;
		}else if("4".equals(orderType)){
			fileName = "自助订单"+fileName;
		}else if("5".equals(orderType)){
			fileName = "会员订单"+fileName;
		}
		List<OrderInFoToTK> dataList = null;
		List<Map<String,Object>> list=createExcelRecord(request);
		String key = new String(request.getParameter("key").getBytes("iso-8859-1"), "utf-8"); 
		String columnName = new String(request.getParameter("columnName").getBytes("iso-8859-1"), "utf-8"); 
		String columnNames[] = columnName.split(",");
        String keys[] = key.split(",");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list,keys,columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        System.err.println("===============================haha================================================");
		return "OK";
	}
	
	/**
	 * 获取导出数据
	 * @param request
	 * @return
	 */
	private List<Map<String, Object>> createExcelRecord(HttpServletRequest request){
		String  orderType = request.getParameter("type");
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		List<OrderInFoToTK> dataList = null;//(List<OrderInFoToTK>) request.getSession().getAttribute("orderListByTK");
		Map<String, Object> map = new HashMap<String, Object>();
		if("1".equals(orderType)){
			dataList = (List<OrderInFoToTK>) request.getSession().getAttribute("orderListByTK");
		}else if("2".equals(orderType)){
			dataList = (List<OrderInFoToTK>) request.getSession().getAttribute("orderListBySJ");
		}else if("3".equals(orderType)){
			dataList = (List<OrderInFoToTK>) request.getSession().getAttribute("orderListByMY");
		}else if("4".equals(orderType)){
			dataList = (List<OrderInFoToTK>) request.getSession().getAttribute("orderListByZZ");
		}else if("5".equals(orderType)){
			List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
			map.put("sheetName", "sheet1");
			listMap = (List<Map<String, Object>>) request.getSession().getAttribute("orderListByHY");
			listMap.add(0, map);
			return listMap;
		}
		
        map.put("sheetName", "sheet1");
        listmap.add(map);
        OrderInFoToTK orderInFoToTK = null;
        for (int j = 0; j < dataList.size(); j++) {
        	orderInFoToTK=dataList.get(j);
            Map<String, Object> mapValue = new HashMap<String, Object>();
            mapValue.put("trade_id",orderInFoToTK.getTrade_id());
            mapValue.put("order_id",orderInFoToTK.getOrder_id());
            mapValue.put("created_time", DateUtils.format(orderInFoToTK.getCreated_time(), DateUtils.datePatternAllHH));
            mapValue.put("order_number", orderInFoToTK.getOrder_number());
            mapValue.put("title", orderInFoToTK.getTitle());
            mapValue.put("nick_name", orderInFoToTK.getNick_name()+"("+orderInFoToTK.getMobile()+")");
            mapValue.put("level", orderInFoToTK.getLevel());
            mapValue.put("prime_price", orderInFoToTK.getPrime_price());
            mapValue.put("person_count", orderInFoToTK.getPerson_count());
            mapValue.put("price1", orderInFoToTK.getPrice1());
            mapValue.put("store_name", orderInFoToTK.getStore_name());
            mapValue.put("periods", orderInFoToTK.getPeriods());
            mapValue.put("coach_name", orderInFoToTK.getCoach_name());
            mapValue.put("overplus_periods", orderInFoToTK.getOverplus_periods());
            mapValue.put("start_time",orderInFoToTK.getStart_time());
            mapValue.put("cash_money",orderInFoToTK.getCash_money());
            listmap.add(mapValue);
        }
		return listmap;
	}
	
	/**
	 * 获取会员订单
	 */
	@Override
	public Map<String,Object> getOrderListByHY(Map<String, Object> map) throws Exception {
		Map<String,Object> responsemap = new HashMap<String,Object>();
		int pageCount = 10 ;
		int pageSum = 0;
		int pageNum = (Integer)map.get("pageNum");
		int pageNo 	= pageNum; 
		if( pageNum != 0){
			pageNum = pageCount * (pageNum-1);
			map.put("pageNum", pageNum);
			map.put("pageCount", pageCount);
		}else{
			map.put("pageCount", pageCount);
		}
		String payTimes = (String) map.get("payTime"); 
		String payTimeArray[] = payTimes.split("~");
		if(payTimes.length() > 0 && payTimes != null){
			map.put("startTime", payTimeArray[0]);
			map.put("endTime", payTimeArray[1]);
		}
		Integer vipType = (Integer) map.get("vipType");
		String vipTypes = "";
		
		List<Map<String,Object>> listAll = new ArrayList<Map<String,Object>>();
		BigDecimal num = new BigDecimal(0);
		List<Map<String,Object>> responseList = new ArrayList<Map<String,Object>>();
		if(vipType == 1){
			vipTypes = "续费";
			map.put("vipType", vipTypes);
		}else if(vipType == 2){
			vipTypes = "新增";
		}else{
			vipTypes = "";
		}
		map.put("vipType", vipTypes);
		responseList  = orderInfoMapper.getOrderListByHY(map);
		map.put("pageNum", null);
		responsemap =  orderInfoMapper.queryVipOrderCount(map);
		responsemap.put("vipType",vipType);
		responsemap.put("pageNum",pageNo);
		responsemap.put("list", responseList);
		responsemap.put("mobile", map.get("mobile"));
		responsemap.put("pay_time",map.get("payTime"));
		responsemap.put("num", num.setScale(2, BigDecimal.ROUND_HALF_UP));
		responsemap.put("payStatus", map.get("payStatus"));
		responsemap.put("listAll", listAll);
		return responsemap;
	}
	
	/**
	 * 私教订单取消
	 * @param courseId
	 * @param orderInfo
	 * @param orderStatus
	 */
	private void cancelPtCourseOrder(int courseId, OrderInfoResultModel orderInfo, String orderStatus){
		logger.info("============pt order cancel update orderStatus start======================");
		CourseInfo courseInfo = courseInfoMapper.selectById(courseId);
		int currentCount = courseInfo.getCurrentCount()-1;
		courseInfo.setCurrentCount(currentCount);
		int bool = courseInfoMapper.updateSelectiveById(courseInfo);
		logger.info("============pt order cancel update orderStatus end:bool"+bool+"====================");
	}
	
	/**
	 * 查询用户消费记录
	 */
	@Override
	public Map<String, Object> getUserOrderListByUser(Map<String, Object> map) {
		Integer pageNo = (Integer) map.get("pageNo");
		Integer pageSize = (Integer) map.get("pageSize");
		Integer pageNow = pageNo ;
		if(pageNo > 1){
			map.put("pageNow", pageNow);
			pageNo = pageSize*(pageNo -1);
			map.put("pageNo", pageNo);
		}else{
			map.put("pageNo", 0);
			map.put("pageNow", 1);
		}
		
		List<Map<String,Object>> listAll = orderInfoMapper.quertyUserOrderInfoList(map);
		BigDecimal amount = new BigDecimal(0);
		BigDecimal primePrice = new BigDecimal(0);
		for(int i=0 ; i < listAll.size() ; i++){
			BigDecimal i_amount = (BigDecimal) listAll.get(0).get("amount1");
			BigDecimal i_primePrice = (BigDecimal) listAll.get(0).get("primePrice");
			amount = amount.add(i_amount);
			primePrice = primePrice.add(i_primePrice);
		}
		map.put("page", "page");
		List<Map<String,Object>> list = orderInfoMapper.quertyUserOrderInfoList(map);
		map.put("pageCount", listAll.size());
		map.put("shifu", amount);
		map.put("feiyong", primePrice);
		map.put("list", list);
		return map;
	}
	
	/**
	 * 部分退款：</br>
	 * 规则：</br>
	 * 1 微信退款 ： 直接走微信退款接口将退款金额传过去 在将订单状态修改为 4 表示退款</br>
	 * 2个人储值卡退款：直接将退款金额加到用户个人账户余额里面 在向个人消费表中插入一条 消费金额但是金额是负数的 在将订单状态修改为 4 表示退款</br>
	 * 3企业退款：将order_info 表中payStatus 状态修改为 5 表示 部分退款 
	 * 		        在将order_info 表中 amount - refundAmt ,company_amt - refundAmt 
	 * 		        在向企业消费记录表中插入一条消费记录并且消费金额是负数的表示退款金额</br>
	 * 4个人+微信：先退个人储值卡在退微信，只有当退款金额大于 个人储值卡消费金额的时候在走微信退款 否则是直接退个人储值卡消费金额 逻辑同上2,1</br>
	 * 5企业+微信：先退企业储值卡在退微信，只有当退款金额大于企业储值卡消费金额的时候在走微信退款 否则是直接退个人储值卡消费金额 逻辑同上3,1</br>
	 * @throws Exception 
	 * 
	 */
	@Override
	public int createdRefundSplitOrder(Map<String, Object> map) throws Exception {
		// TODO Auto-generated method stub
		logger.info("===============================createdRefundSplitOrder start =================================");
		Integer orderId = (Integer) map.get("orderId");
		SysUser sysUser = (SysUser) map.get("sysUser");
		BigDecimal refundAmt = (BigDecimal) map.get("refundAmt");// 退款金额
		Map<String,Object> refundMap = new HashMap<String,Object>();
		OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
		int count = orderInfoMapper.queryOrderRefundByOrderId(orderId);
		UserInfo userInfo  = userInfoMapper.selectById(orderInfo.getUserId());
		List<OrderRefund> listRefund = new ArrayList<>();
		String remark = (String) map.get("remark");
		// 防止进行多次退款操作
		if(count > 0){
			logger.info("==================== createdRefundSplitOrder msg 已经退款过了！");
			return 1;
		}
		if(orderInfo != null){
			// 根据支付类型 进行退款操作
			switch (orderInfo.getPayType()) {
			// 微信在线支付
			case OrderContants.PAY_TYPE_WECHAT:
				refundMap = wechatOrderRefund(orderInfo, refundAmt, sysUser, remark != null ? remark : "退到微信账户中");
				if("SUCCESS".equals(refundMap.get("result_code"))){
					listRefund.add((OrderRefund)refundMap.get("wechatOrderRefund"));
				}
				break;
			// 个人储值卡支付	
			case OrderContants.PAY_TYPE_PERSON_ACCOUNT:
				refundMap = personOrderRefund(orderInfo, orderInfo.getConsumeAmt(), refundAmt, sysUser, userInfo, remark != null ? remark : "退款到个人储值卡账户");
				if("SUCCESS".equals(refundMap.get("result_code"))){
					listRefund.add((OrderRefund)refundMap.get("personOrderRefund"));
				}
				break;
			// 企业支付	
			case OrderContants.PAY_TYPE_COMPANY_ACCOUNT:
				refundMap = companyOrderRefund(orderInfo,orderInfo.getCompanyAmt(), refundAmt, sysUser, remark != null ? remark : "退款企业储值卡中");
				// 如果是部分退款的话就用 就用消费的金额减去退款的部分退款金额
				orderInfo.setAmount(orderInfo.getAmount().subtract(refundAmt));
				orderInfo.setCompanyAmt(orderInfo.getCompanyAmt().subtract(refundAmt));
				if("SUCCESS".equals(refundMap.get("result_code"))){
					listRefund.add((OrderRefund)refundMap.get("companyOrderRefund"));
				}
				break;
			// 个人+微信支付 	
			case OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT:
				// 微信+个人储值卡支付退款
				// step 1先退个人储值卡的金额
				BigDecimal personAccountRefundAmt = orderInfo.getConsumeAmt();// 个人储值卡实付金额
				BigDecimal tatolPersonAmt = orderInfo.getConsumeAmt();// 个人储值卡实付金额
				// step 2 判断一下退款的金额是否大于 个人储值卡实付金额
				if(refundAmt.compareTo(personAccountRefundAmt) <= 0){
					personAccountRefundAmt = refundAmt;
					refundAmt = BigDecimal.ZERO;// 当退款金额小于等于个人储值卡金额的时候是不走微信退款的
				}else{
					refundAmt = refundAmt.subtract(personAccountRefundAmt);
				}
				refundMap = personOrderRefund(orderInfo, tatolPersonAmt, personAccountRefundAmt, sysUser, userInfo, remark != null ? remark : "退款到个人储值卡账户");
				if("SUCCESS".equals(refundMap.get("result_code"))){
					listRefund.add((OrderRefund)refundMap.get("personOrderRefund"));
				}
				// 只有退款金额大于0 的时候才走微信退款
				if("SUCCESS".equals((String)refundMap.get("result_code"))
						&& refundAmt.compareTo(BigDecimal.ZERO) > 0){
					// 3再退微信支付金额
					refundMap = wechatOrderRefund(orderInfo, refundAmt, sysUser, remark != null ? remark : "退到微信账户中");
					if("SUCCESS".equals(refundMap.get("result_code"))){
						listRefund.add((OrderRefund)refundMap.get("wechatOrderRefund"));
					}else {
						throw new Exception();
					}
				}else if(refundAmt.compareTo(BigDecimal.ZERO) == 0){
					refundMap.put("result_code", "SUCCESS");
					refundMap.put("err_code","退款成功");
				}else{
					refundMap.put("result_code", "FAIL");
					refundMap.put("err_code","退款失败");
					throw new Exception();
				}
				break;
			case OrderContants.PAY_TYPE_COMPANY_WECHAT_ACCOUNT: 
				// 先退企业支付金额在退微信支付金额
				// step 1 先获取企业支付金额
				BigDecimal companyAccountRefundAmt = orderInfo.getCompanyAmt();// 企业储值卡实付金额
				BigDecimal totalCompanyAmt =  orderInfo.getCompanyAmt();// 企业储值卡实付金额
				// step 2 退款金额小于等于退款金额 的时候 就不走微信退款
				if(refundAmt.compareTo(companyAccountRefundAmt) <= 0){
					orderInfo.setAmount(orderInfo.getAmount().subtract(refundAmt));
					orderInfo.setCompanyAmt(orderInfo.getCompanyAmt().subtract(refundAmt));
					companyAccountRefundAmt = refundAmt ;
					refundAmt = BigDecimal.ZERO;
				}else{
					refundAmt = refundAmt.subtract(companyAccountRefundAmt);
					orderInfo.setAmount(orderInfo.getAmount().subtract(orderInfo.getCompanyAmt()));
					orderInfo.setCompanyAmt(new BigDecimal(0));
					
				}
				refundMap = companyOrderRefund(orderInfo,totalCompanyAmt, companyAccountRefundAmt, sysUser, remark != null ? remark : "退款企业储值卡中");
				if("SUCCESS".equals(refundMap.get("result_code"))){
					listRefund.add((OrderRefund)refundMap.get("companyOrderRefund"));
				}
				if("SUCCESS".equals((String)refundMap.get("result_code")) 
						&& refundAmt.compareTo(BigDecimal.ZERO) > 0){
					// 3再退微信支付金额
					BigDecimal wechatTotalAmt = orderInfo.getWeixinAmt();
					refundMap = wechatOrderRefund(orderInfo, refundAmt, sysUser, remark != null ? remark : "退到微信账户中");
					if("SUCCESS".equals(refundMap.get("result_code"))){
						listRefund.add((OrderRefund)refundMap.get("wechatOrderRefund"));
					}else {
						throw new Exception();
					}
				}else if(refundAmt.compareTo(BigDecimal.ZERO) == 0){
					// 只是退企业支付金额 的部分金额
					refundMap.put("result_code", "SUCCESS");
					refundMap.put("totalAmt", orderInfo.getAmount());
					refundMap.put("refundAmt", companyAccountRefundAmt);
					refundMap.put("refund_id",String.valueOf(orderInfo.getId()));
				}else{
					refundMap.put("result_code", "FAIL");
					refundMap.put("NOTENOUGH","退款失败");
					throw new Exception();
				}
				break;
			default:	
				refundMap.put("msg", "支付类型错误！");
				refundMap.put("status", false);
			}
			if("SUCCESS".equals((String)refundMap.get("result_code"))){
				orderInfo.setPayStatus(OrderContants.PayStatus.PARTIAL_REFUND);
				orderInfo.setOrderStatus(OrderContants.OrderStatus.CANCEL.getStatus());
				orderInfo.setCancelBackmoney(0);// 表示不可退款的金额部分
				orderInfo.setUpdatedTime(new Date());
				orderInfo.setUpdatedBy(sysUser.getId());
				orderInfoMapper.updateSelectiveById(orderInfo);
				updateVipOrder(orderInfo, userInfo);
				orderInfoMapper.createdRefundOrderList(listRefund);
				return 1;
			}else if("FAIL".equals(refundMap.get("result_code"))){
				if("NOTENOUGH".equals(refundMap.get("err_code"))){
					return -2;
				}
				return -1;
			}
			
		}else{
			logger.info("=====================createdRefundSplitOrder error : 找不到该订单！");
			return -3;
		}
		
		return -1;
	} 
	
	/**
	 * 创建企业员工用户消费记录表
	 * @param orderInfo		
	 * @param totalAmount
	 * @param refundAmount
	 * @return
	 */
	public Map<String,Object> createCompanyStaffConsume(OrderInfo orderInfo, BigDecimal totalAmount, BigDecimal refundAmount){
		Map<String,Object> refundMap = new HashMap<>();
		CompanyStaffConsume companyStaffConsumeQuery = new CompanyStaffConsume();
		companyStaffConsumeQuery.setOrderId(orderInfo.getId());
		companyStaffConsumeQuery.setOrderStatus(OrderContants.OrderStatus.NORMAL.getIndex());
		CompanyStaffConsume companyStaffConsume = companyStaffConsumeMapper.selectOne(companyStaffConsumeQuery);
		if (companyStaffConsume != null && companyStaffConsume.getId() != null) {
			companyStaffConsume.setId(null);
			companyStaffConsume.setPayTime(null);
			companyStaffConsume.setCancelTime(new Date());
			companyStaffConsume.setAmount(refundAmount);
			companyStaffConsume.setOrderStatus(OrderContants.OrderStatus.CANCEL.getIndex());
		}
		boolean boolC = companyStaffConsumeMapper.insertSelective(companyStaffConsume) > 0;
		if(!boolC){
			refundMap.put("result_code", "FAIL");
			refundMap.put("NOTENOUGH","退款失败");
		}else{
			refundMap.put("result_code", "SUCCESS");
			refundMap.put("refund_id",String.valueOf(orderInfo.getId()));
		}
		return refundMap;
	}
	
	/**
	 * 创建订单退款记录
	 * @param orderInfo			订单信息
	 * @param refundType		退款类型
	 * @param refundStatus		退款状态	success
	 * @param refundOrderId		退款订单号
	 * @param totalAmount		退款总金额
	 * @param refundAmount		退款金额
	 * @param sysUser			管理人员
	 * @param remark			备注
	 * @return
	 */
	public OrderRefund createOrderRefund(OrderInfo orderInfo, Integer refundType, String refundStatus, String refundOrderId, BigDecimal totalAmount, BigDecimal refundAmount, SysUser sysUser,String remark){
		OrderRefund orderRefund = new OrderRefund();
		orderRefund.setOrderId(orderInfo.getId());
		orderRefund.setRefundType(refundType);
		orderRefund.setRefundNo(refundOrderId);
		orderRefund.setRefundFee(refundAmount.doubleValue());
		orderRefund.setTotalFee(totalAmount.doubleValue());
		orderRefund.setRefundStatus(refundStatus);//这里统一给退款中,然后在每天跑定时任务的时候在更新状态值
		orderRefund.setUserId(orderInfo.getUserId());
		orderRefund.setRefundChanne("original");
		orderRefund.setRefundFashion("1");
		orderRefund.setCreatedTime(new Date());
		orderRefund.setCreatedBy(String.valueOf(sysUser.getId()));
		orderRefund.setRemark(remark);
		return orderRefund;
	}
	
	/**
	 * 退款优惠券
	 */
	public void returnCoupon(Long couponDetailId){
		CouponDetail couponDetail = couponDetailMapper.selectByPrimaryKey(couponDetailId);
		if(couponDetail!=null){
			couponDetail.setIsUsed(0);
			couponDetail.setUseTime(null);
			couponDetailMapper.updateByPrimaryKey(couponDetail);
		}
	}
	
	/**
	 * 微信退款
	 * 逻辑：微信退款是将 订单总金额 和退款金额传给微信退款接口即可
	 * 在根据返回的状态吗来判断是否退款成功
	 * 返回状态吗：NOTENOUGH（公司账户余额不足） SUCCESS (退款成功) 
	 * @param orderInfo	订单信息
	 * @param refundAmt	退款金额
	 * @param sysUser	管理员
	 * @return
	 */
	public Map<String, Object> wechatOrderRefund(OrderInfo orderInfo,BigDecimal refundAmt,SysUser sysUser,String remark){
		logger.info("========================createdRefundSplitOrder wechat pay type start =======================");
		Map<String,Object> refundMap = new HashMap<>();
		// 微信退款
		refundMap = RefundUtil.wechatRefund1(orderInfo.getOrderNumber(), orderInfo.getWeixinAmt(),refundAmt);
		if("SUCCESS".equals(refundMap.get("result_code"))){
			// 退款成功  向退款表中插入一条数据
			String refundId =(String) refundMap.get("refund_id");
			OrderRefund wechatOrderRefund = createOrderRefund(orderInfo, orderInfo.getOrderType(), "success", refundId, orderInfo.getWeixinAmt(), refundAmt, sysUser,remark);
			refundMap.put("wechatOrderRefund", wechatOrderRefund);
		}
		
		logger.info("========================createdRefundSplitOrder wechat pay type end =========================");
		return refundMap;
	}
	
	/**
	 * 个人储值卡退款
	 * 逻辑：直接将退款金额加到用户的个人储值卡上
	 * @param orderInfo
	 * @param refundAmt
	 * @param sysUser
	 * @return
	 */
	public Map<String, Object> personOrderRefund(OrderInfo orderInfo,BigDecimal tatolPersonAmt, BigDecimal refundAmt, SysUser sysUser, UserInfo userInfo, String remark){
		Map<String,Object> refundMap = new HashMap<>();
		UserAccountConsume userAccountConsume = new UserAccountConsume();
		String consumeType = null;
		if(orderInfo.getOrderType() != 5 && orderInfo.getOrderType() != 7){
			consumeType = "1";
		}else{
			consumeType = "2";
		}
		// 将退款金额退回个人账户
		userInfo.setAccountAmt(userInfo.getAccountAmt().add(refundAmt));
		userInfoMapper.updateSelectiveById(userInfo);
		// 但是插入用户消费表的时候就要表示用户全部退款
		Integer inserCount = createUserAccountConsume(orderInfo.getUserId(), consumeType, refundAmt.multiply(new BigDecimal("-1")), orderInfo.getId(), remark);
		// 插入退款表的时候就是插入实际退给用户的到账金额
		OrderRefund personOrderRefund = createOrderRefund(orderInfo, 2, "success", orderInfo.getOrderNumber(), tatolPersonAmt, refundAmt, sysUser, remark);
		if(inserCount > 0){
			refundMap.put("result_code", "SUCCESS");
			refundMap.put("refund_id",String.valueOf(orderInfo.getId()));
			refundMap.put("personOrderRefund", personOrderRefund);
		}else{
			refundMap.put("result_code", "FAIL");
			refundMap.put("err_code","ERROR");
		}
		return refundMap;
	}
	
	/**
	 * 企业储值卡退款
	 * 
	 * @param orderInfo
	 * @param refundAmt
	 * @param sysUser
	 * @return
	 */
	public Map<String, Object> companyOrderRefund(OrderInfo orderInfo,BigDecimal companyAmt, BigDecimal refundAmt, SysUser sysUser, String remark){
		Map<String,Object> refundMap = new HashMap<>();
		// 向企业账户退款
		Integer insertCount = createCompanyStaffConsume(orderInfo, refundAmt);
		// 向退款表中插入用户退款金额
		OrderRefund companyOrderRefund = createOrderRefund(orderInfo, 3, "success", orderInfo.getOrderNumber(), companyAmt, refundAmt, sysUser, remark);
		if(insertCount > 0){
			
			refundMap.put("result_code", "SUCCESS");
			refundMap.put("totalAmt", orderInfo.getAmount());
			refundMap.put("totalAmt", refundAmt);
			refundMap.put("refund_id",String.valueOf(orderInfo.getId()));
			refundMap.put("companyOrderRefund", companyOrderRefund);
			logger.info("=========================================createdRefundSplitOrder PAY_TYPE_COMPANY_ACCOUNT RefundOrder  SUCCESS=====================");
		}else{
			
			refundMap.put("result_code", "FAIL");
			refundMap.put("NOTENOUGH","退款失败");
			logger.info("=========================================createdRefundSplitOrder PAY_TYPE_COMPANY_ACCOUNT RefundOrder  FAIL=====================");
		}
		return refundMap;
	}
	
	/**
	 * 插入个人储值卡消费记录
	 * @param userId
	 * @param consumeType
	 * @param refundAmt
	 * @param orderId
	 * @param remark
	 * @return
	 */
	public Integer createUserAccountConsume(Integer userId, String consumeType, BigDecimal refundAmt, Integer orderId, String remark){
		UserAccountConsume userAccountConsume = new UserAccountConsume();
		userAccountConsume.setUserId(userId);
		userAccountConsume.setConsumeType(consumeType);
		userAccountConsume.setConsumeAmt(refundAmt);
		userAccountConsume.setOrderId(orderId);
		userAccountConsume.setRemark(remark);
		userAccountConsume.setCreateTime(new Date());
		Integer inserCount = userAccountConsumeMapper.insertSelective(userAccountConsume);
		return inserCount;
	}
	
	/**
	 * 插入企业退款记录
	 * 逻辑：当退款的时候分为两种情况
	 * 1 全额退款的时候 向企业消费记录表中插入一条记录  消费金额(负数)等于支付金额为 
	 * 2 部分退款的时候 退了多少钱就向消费记录表中插入一条记录  消费金额(负数)等于退款金额 
	 * @param orderInfo
	 * @param refundAmt
	 * @return
	 */
	public Integer createCompanyStaffConsume(OrderInfo orderInfo, BigDecimal refundAmt){
		CompanyStaffConsume companyStaffConsumeQuery = new CompanyStaffConsume();
		companyStaffConsumeQuery.setOrderId(orderInfo.getId());
		companyStaffConsumeQuery.setOrderStatus(OrderContants.OrderStatus.NORMAL.getIndex());
		CompanyStaffConsume companyStaffConsume =  companyStaffConsumeMapper.selectOne(companyStaffConsumeQuery);
		CompanyStaffConsume companyStaffConsumeRefund = new CompanyStaffConsume();
		companyStaffConsumeRefund.setAmount(refundAmt);
		companyStaffConsumeRefund.setOrderId(orderInfo.getId());
		companyStaffConsumeRefund.setCompanyStaffId(companyStaffConsume.getCompanyStaffId());
		companyStaffConsumeRefund.setPayTime(null);
		companyStaffConsumeRefund.setCancelTime(new Date());
		companyStaffConsumeRefund.setUserId(orderInfo.getUserId());
		companyStaffConsumeRefund.setOrderStatus(OrderContants.OrderStatus.CANCEL.getIndex());
		int insertCount = companyStaffConsumeMapper.insertSelective(companyStaffConsumeRefund) ;
		return insertCount;
	}
	
	/**
	 * 修改vip 订单
	 * 
	 * @param orderInfo
	 * @throws Exception 
	 */
	public void updateVipOrder(OrderInfo orderInfo,UserInfo userInfo) {
		if(orderInfo.getOrderType().intValue() == OrderContants.OrderType.vip_order.getIndex()){
			try {
				VipPurchaseLog vipPurchaseLog = vipPurchaseLogMapper.quertVipPurchaseLogByOrderId(orderInfo.getId());
				UserProductService userProductService = userProductServiceMapper.queryUserProductServiceToUserLevel(userInfo.getId());
				Integer surplusDay = DateUtils.daysBetween(new Date(), userProductService.getEndDate());// 剩余天数
				Integer vipLogDay = DateUtils.daysBetween(vipPurchaseLog.getStartTime(), vipPurchaseLog.getEndTime());// 购买服务的天数
				Date endDate = new Date();
				Date startDate = vipPurchaseLog.getStartTime();
				Integer level = UserConstants.UserLevel.user.getIndex() ;
				String  productServiceType = "1";
				// 如果服务剩余天数大于购买服务的天数表示该用户是续费用户 
				if (surplusDay > vipLogDay) {
					// 如果是续费用户就用结束时间减去购买服务的日期
					endDate = DateUtils.AddDays(userProductService.getEndDate(), -vipLogDay);
					level = UserConstants.UserLevel.vip.getIndex() ;
					productServiceType = "2";
					startDate = new Date();
					
				} 
				// 檬会员订单
				// 修改用户的到期时间为今天
				userInfo.setVipEndTime(DateUtils.getDateShort(endDate));
				userInfo.setLevel(level);
				// 修改会员日志表到期时间为今天
				vipPurchaseLog.setStartTime(startDate);
				vipPurchaseLog.setEndTime(DateUtils.getDateShort(new Date()));
				// 修改用户产品服务表到期时间为今天
				userProductService.setEndDate(DateUtils.getDateShort(endDate));
				userProductService.setProductServiceType(productServiceType);
				userInfoMapper.updateSelectiveById(userInfo);
				vipPurchaseLogMapper.updateByPrimaryKeySelective(vipPurchaseLog);
				userProductServiceMapper.updateSelectiveById(userProductService);
			} catch (Exception e) {
				// TODO: handle exception
				logger.error("=============== updateVipOrder error:"+e.toString()+e.getCause(),e);
			}
			
		}
	}
	

}
